package com.xx566.blog.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.xx566.blog.model.Article;
import com.xx566.blog.model.Friendly;
import com.xx566.blog.model.Message;
import com.xx566.blog.model.Tags;
import com.xx566.blog.model.User;

public class XX566TestController extends Controller {

	public void save() {
		Map<String, Object> attrs = new HashMap<String, Object>();
		attrs.put("name", "糗事百科");
		attrs.put("url", "www.qiushibaike.com");
		Friendly friendly = getModel(Friendly.class).setAttrs(attrs);
		friendly.save();
		System.out.println(friendly.getInt("id"));
		redirect("/");
	}

	public void update() {
		int id = getParaToInt();
		Friendly friendly = getModel(Friendly.class).findById(id);
		int count = friendly.getInt("counts");
		count++;
		friendly.set("counts", count);
		if (friendly.update()) {
			redirect(friendly.getStr("url"));
		}
	}

	public void toSaveUser() {
		render("toSaveUser.jsp");
	}

	public void saveUser() {
		if (getModel(User.class).save())
			System.out.println("保存成功");
		render("test-redirect.jsp");
	}

	public void toSaveArticle() {
		render("toSaveArticle.jsp");
	}

	public void saveArticle() {
		if (getModel(Article.class).save())
			System.out.println("保存成功");
		forwardAction("/test/toSaveArticle/");
	}

	public void toSaveMessage() {
		render("toSaveMessage.jsp");
	}

	public void saveMessage() {
		if (getModel(Message.class).save())
			System.out.println("保存成功");
		forwardAction("/test/toSaveMessage/");
	}

	public void ztree() {
		List<Tags> tags = CacheKit.get("tags", "tags", new IDataLoader() {
			@Override
			public Object load() {
				return Tags.dao.findAll();
			}
		});
		Map<String, String> map = new HashMap<String, String>();
		List<String> list = new ArrayList<String>();
		int count = 0;
		for (Tags tag : tags) {
			String str = "";
			if (!map.containsKey(tag.getStr("type"))) {
				count--;
				str += "{id:" + count + ",";
				str += "pId:0,";
				str += "name:'" + tag.getStr("type") + "'}";
				map.put(tag.getStr("type"), String.valueOf(count));
				list.add(str);
			} 
			str = "{id:" + tag.getLong("id") + ",";
			str += "pId:" + map.get(tag.getStr("type")) + ",";
			str += "name:'" + tag.getStr("name") + "'}";
			list.add(str);
		}
		setAttr("tags", list.toString());
		render("ztreeleft.jsp");
	}
}
